/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.dispensedrug.client.widget;

import java.util.List;

import net.carefx.framework.container.client.context.AppContext;

import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.web.gwt.client.widget.FcMessageBox;
import com.th.supcom.pds.auditprescription.client.model.PdsPrescDetailCombineModel;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.client.model.PdsSupplyDetailModel;
import com.th.supcom.pds.common.client.model.PdsSupplyModel;
import com.th.supcom.pds.common.client.widget.PdsGrid;
import com.th.supcom.pds.common.client.widget.PrescDetailGrid;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.dispensedrug.client.service.DispenseDrugRpc;
import com.th.supcom.pds.dispensedrug.client.service.DispenseDrugRpcAsync;
import com.th.supcom.pds.internal.client.model.PatientInfoModel;
import com.th.supcom.pds.internal.client.model.ResultModel;
import com.th.supcom.pds.prescstatusquery.client.widget.SupplyStatusQueryWindow;

/**
 * 核对发药Action
 * 
 * @author 杨冲
 */
public class DispenseDrugAction {
	private static final DispenseDrugRpcAsync s_DISPENSEDRUGRPCASYNC = GWT
			.create(DispenseDrugRpc.class);
	/** 提交路径. */
	public static final String SCC_BRANCH = "$URL$";

	/** 提交日期. */
	public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";
	/** 最终修改人员. */
	public static final String SCC_LAST_MODIFIER_NAME = "$Author$";
	/** 最终版本号. */
	public static final String SCC_REVISION = "$Revision$";

	private DispenseDrugFields m_dispenseDrugFields;

	private DispenseDrugRecipeDetailPanel m_dispenseDrugRecipeDetailPanel;

	private DispenseDrugRecipePanel m_dispenseDrugRecipePanel;

	/**
	 * 构造函数
	 */
	public DispenseDrugAction() {

	}

	/**
	 * 清除
	 */
	public void clear() {

		m_dispenseDrugFields.getPrescSource().clear();
		m_dispenseDrugFields.getSexField().clear();
		m_dispenseDrugFields.getConsumeProofField().clear();
		m_dispenseDrugFields.getBirthDateField().clear();
		m_dispenseDrugFields.getMoneySumField().clear();
		m_dispenseDrugFields.getNameField().clear();
		m_dispenseDrugFields.getPatientIdField().clear();
		m_dispenseDrugFields.getRecipeNoField().clear();
		m_dispenseDrugFields.getTransfuseDispenseField().clear();
		m_dispenseDrugRecipeDetailPanel.getGrid().clear();
		m_dispenseDrugFields.getConsumeProofField().focus();
		m_dispenseDrugFields.getVisitTypeNameField().clear();
		m_dispenseDrugFields.getVisitIdField().clear();
		m_dispenseDrugFields.getVisitBeginDateField().clear();
		m_dispenseDrugFields.getDeptNameField().clear();
		m_dispenseDrugFields.getDay().clear();
		m_dispenseDrugFields.getNumber().clear();
	}

	private void initPatientInfo(PatientInfoModel model) {
		DateTimeFormat dtFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
		if(model==null){
			return;
		}
		m_dispenseDrugFields.getSexField().setValue(model.getSex());
		m_dispenseDrugFields.getBirthDateField().setValue(
				dtFormat.format(model.getBirthDate()));
		if (model.getBalance() != null) {
			m_dispenseDrugFields.getMoneySumField().setValue(
					String.valueOf(model.getBalance()));
		}
		m_dispenseDrugFields.getNameField().setValue(model.getName());
		m_dispenseDrugFields.getPatientIdField().setValue(model.getPatiId());

		m_dispenseDrugFields.getVisitTypeNameField().setValue(
				model.getChargeType() == null ? "" : model.getChargeType());
		if (model.getVisitId() != null) {
			m_dispenseDrugFields.getVisitIdField().setValue(
					model.getVisitId() + "");
		}
		if (model.getVisitBeginDates() != null) {
			m_dispenseDrugFields.getVisitBeginDateField().setValue(
					dtFormat.format(model.getVisitBeginDates()));
		}
		m_dispenseDrugFields.getDeptNameField().setValue(model.getDeptName());
		if (model.getVisitDay() != null) {
			m_dispenseDrugFields.getDay().setValue(model.getVisitDay() + "");
		}
		m_dispenseDrugFields.getNumber().setValue(model.getBedCode());

	}

	/**
	 * 发药
	 */
	public void dispenseDrug(final Component sucessComponent,
			final Component failComponent) {

		final List<PdsSupplyDetailModel> models = m_dispenseDrugRecipeDetailPanel
				.getGrid().getDetailData();
		if (null == models || models.isEmpty()) {
			ClientUtils.alertMessageBox("没有处方明细信息，无法发药!", failComponent);
			return;
		}
		final String operator = ClientUtils.geteEmpModel().getEmpCode();
		FcMessageBox.confirm(CodeConstants.PROMPT, "确认发药？",
				new Listener<MessageBoxEvent>() {

					@Override
					public void handleEvent(final MessageBoxEvent be) {
						String info = be.getButtonClicked().getItemId();
						String patientId = m_dispenseDrugFields
								.getPatientIdField().getValue();
						if (Dialog.YES.equals(info)) {
							executeDispenseDrug(models, operator, patientId,
									sucessComponent, failComponent);
						}
						return;
					}
				});

	}

	private void executeDispenseDrug(final List<PdsSupplyDetailModel> models,
			final String operator, String patientId,
			final Component sucessComponent, final Component failComponent) {
		String deptCode = ClientUtils.getOrgModel().getOrgCode();
		s_DISPENSEDRUGRPCASYNC.dispenseDrug(models, operator, deptCode,
				patientId, new AsyncCallback<Void>() {

					@Override
					public void onFailure(final Throwable caught) {
						ClientUtils.alertMessageBox(
								caught.getLocalizedMessage(), failComponent);
					}

					@Override
					public void onSuccess(final Void result) {
						Info.display(CodeConstants.PROMPT, "发药成功");
						findRecipeByCondition(sucessComponent, failComponent);
						clear();
					}
				});
	}

	/**
	 * 查询核对发药界面的所有处方主记录，当前窗口处方主记录，处方明细表
	 */
	public void findAllRecipeDataByRcptNo(final Component sucessComponent,
			final Component failComponent) {
		findRecipeDetailDataByRcptNo(sucessComponent, failComponent);
		findRecipeByCondition(sucessComponent, failComponent);
	}

	/**
	 * 初始化处方数据，查询所有的未发药记录
	 */
	public void findRecipeByCondition(final Component sucessComponent,
			final Component failComponent) {
		final PdsGrid<PdsSupplyModel> grid = m_dispenseDrugRecipePanel
				.getGridPanel();
		String IP = AppContext.get().get("IP");
		String deptCode = ClientUtils.getOrgModel().getOrgCode();

		s_DISPENSEDRUGRPCASYNC.findPdsSupplyListWithTotalPrice(deptCode, IP,
				new AsyncCallback<List<PdsSupplyModel>>() {

					@Override
					public void onFailure(final Throwable caught) {
						ClientUtils.alertMessageBox(
								caught.getLocalizedMessage(), failComponent);
					}

					@Override
					public void onSuccess(final List<PdsSupplyModel> result) {
						grid.getListStore().removeAll();
						grid.getListStore().add(result);
						if (!result.isEmpty()) {
							m_dispenseDrugFields.getPrescSource().setValue(
									result.get(0).getPrescSourceName());
						}

						if (null != sucessComponent) {
							sucessComponent.focus();
						}
					}
				});

	}

	/**
	 * 初始化处方详情数据
	 * 
	 * @param PdsPrescDetailInfoModel
	 */
	public void findRecipeDetailData(
			final PdsSupplyDetailModel pdsSupplyDetailModel) {

		m_dispenseDrugRecipeDetailPanel.mask("正在拼命加载中");
		s_DISPENSEDRUGRPCASYNC.getPdsSupplyDetailListByRcptNo(null,
				pdsSupplyDetailModel.getPrescNo(),
				pdsSupplyDetailModel.getPerformedBy(),
				new AsyncCallback<ResultModel>() {

					@Override
					public void onSuccess(ResultModel result) {
						m_dispenseDrugRecipeDetailPanel.unmask();

						initPatientInfo(result.getPatientInfoModel());
						final PrescDetailGrid<PdsSupplyDetailModel> grid = m_dispenseDrugRecipeDetailPanel
								.getGrid();
						grid.refresh(result.getPdsSupplyDetailModels());
					}

					@Override
					public void onFailure(Throwable caught) {
						m_dispenseDrugRecipeDetailPanel.unmask();
						ClientUtils.alertMessageBox(
								caught.getLocalizedMessage(),
								m_dispenseDrugFields.getConsumeProofField());

					}
				});

	}

	/**
	 * 根据处方号和消费凭证号查询处方明细信息
	 * 
	 * @param successComponent
	 * @param failComponent
	 */
	public void findRecipeDetailDataByRcptNo(final Component successComponent,
			final Component failComponent) {
		final String rcptNo = m_dispenseDrugFields.getConsumeProofField()
				.getValue();

		final String prescNo = m_dispenseDrugFields.getRecipeNoField()
				.getValue();
		if (null == rcptNo && null == prescNo) {
			ClientUtils.alertMessageBox("请输入查询条件", failComponent);
			return;
		}
		s_DISPENSEDRUGRPCASYNC.getPdsSupplyDetailListByRcptNo(rcptNo, prescNo,
				ClientUtils.getOrgModel().getOrgCode(),
				new AsyncCallback<ResultModel>() {
					@Override
					public void onFailure(final Throwable caught) {
						ClientUtils.alertMessageBox(
								caught.getLocalizedMessage(), failComponent);
					}

					@Override
					public void onSuccess(ResultModel result) {
						int size=m_dispenseDrugRecipePanel.getGridPanel().getGrid().getStore().getModels().size();
						if(size==0){
							result=null;
						}
						if (result == null) {
							final PdsSupplyModel currentCondition = new PdsSupplyModel();
							final String rcptNo = m_dispenseDrugFields
									.getConsumeProofField().getValue();
							currentCondition.setRcptNo(rcptNo);
							currentCondition.setPrescNo(m_dispenseDrugFields
									.getRecipeNoField().getValue());
							final SupplyStatusQueryWindow window = new SupplyStatusQueryWindow(
									currentCondition, failComponent);
							window.show();
							return;
						}
						initPatientInfo(result.getPatientInfoModel());

						final PrescDetailGrid<PdsSupplyDetailModel> grid = m_dispenseDrugRecipeDetailPanel
								.getGrid();
						grid.refresh(result.getPdsSupplyDetailModels());

						if (null != successComponent) {
							successComponent.focus();
						}
					}
				});
	}

	/**
	 * 设置核对发药组件类
	 * 
	 * @param dispenseDrugFields
	 */
	public void setDispenseDrugFields(
			final DispenseDrugFields dispenseDrugFields) {

		this.m_dispenseDrugFields = dispenseDrugFields;
	}

	/**
	 * 设置核对发药处方详细信息面板
	 * 
	 * @param dispenseDrugRecipeDetailPanel
	 */
	public void setDispenseDrugRecipeDetailPanel(
			final DispenseDrugRecipeDetailPanel dispenseDrugRecipeDetailPanel) {

		this.m_dispenseDrugRecipeDetailPanel = dispenseDrugRecipeDetailPanel;
	}

	/**
	 * 设置核对发药所有未摆药处方面板
	 * 
	 * 
	 * @param dispenseDrugRecipePanel
	 */
	public void setDispenseDrugRecipePanel(
			final DispenseDrugRecipePanel dispenseDrugRecipePanel) {

		this.m_dispenseDrugRecipePanel = dispenseDrugRecipePanel;
	}
}
